package org.xiaoyu.rpc.registry.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.common.constant.RpcError;
import org.xiaoyu.rpc.common.exception.RpcException;
import org.xiaoyu.rpc.common.url.URL;
import org.xiaoyu.rpc.registry.Registry;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static org.xiaoyu.rpc.registry.nacos.support.ThrowableConsumer.execute;

/**
 * Created By Have
 * 2021/7/12 16:15
 */
@Slf4j
public class NacosRegistry implements Registry {
    private NacosNamingServiceWrapper namingService;
    private Properties reigstryAttribute;

    private static final Set<String> serviceNames = new ConcurrentHashSet<>();
    private static final Map<String, URL> urls = new ConcurrentHashMap<>();

    public NacosRegistry(Properties properties, NacosNamingServiceWrapper namingService) {
        this.namingService = namingService;
        reigstryAttribute = properties;
    }

    @Override
    public void register(URL url) {
        if (serviceNames.contains(url.getServiceUniqueName())) {
            if (log.isErrorEnabled()) {
                log.error("Duplicated service name:[{}]", url.getServiceUniqueName());
            }
            throw new RpcException(RpcError.DUPLICATED_SERVICE_NAME);
        }
        try {
            namingService.registerService(url);
        } catch (NacosException e) {
            if (log.isErrorEnabled()) {
                log.error("Connect Nacos fail", e);
                throw new RpcException(e.getMessage());
            }
        }
    }

    @Override
    public void unRegister(URL url) {

    }

    @Override
    public void destroy() {

    }


}
